

import fs from "fs";
import path from "path";
// import { dirU } from "./common";

/**
 * 删除文件
 * @param {*} path
 */
export function delDir(path: string) {
    let files = [];
    if (fs.existsSync(path)) {
        files = fs.readdirSync(path);
        for (let file of files) {
            // + dirU
            let curPath = path + file;
            if (fs.statSync(curPath).isDirectory()) {
                delDir(curPath);
            } else {
                fs.unlinkSync(curPath);
            }
        }
        fs.rmdirSync(path);
    }
}


/**
 * 递归创建文件夹
 * @param {*} path
 */
export function mkdirpSync(path: string) {
    if (!path) {
        return;
    }
    if (!fs.existsSync(path)) {
        //mkdirpSync(path.substring(0, path.lastIndexOf("/")));
        fs.mkdirSync(path, { recursive: true });
    }
}

/**
 * 复制文件
 * @param src 
 * @param dest 
 * @param pipeFn 
 */
export async function copyDir(src: string, dest: string, pipeFn: (path: string) => void) {
    if (!fs.existsSync(dest)) mkdirpSync(dest);
    const items = fs.readdirSync(src);
    for (const item of items) {
        const srcPath = path.join(src, item);
        const destPath = path.join(dest, item);
        const stat = fs.statSync(srcPath);
        if (stat.isDirectory()) {
            await copyDir(srcPath, destPath, pipeFn);
        } else {
            await fs.copyFileSync(srcPath, destPath);
            if (pipeFn) {
                await pipeFn(destPath);
            }
        }
    }
}



// 用于创建文件夹并复制文件
export async function createDirsAndCopyFile(filePath: string, outPath: string) {
    const dirPath = path.dirname(outPath);
    await mkdirpSync(dirPath)
    await fs.copyFileSync(filePath, outPath);

    // const targetPath = path.resolve(dirPath, path.basename(filePath));
    // // 确保目标目录存在
    // ensureDir(dirPath);
    // // 复制文件到目标位置
    // const sourceFile = outPath; // 替换为源文件的实际路径
    // copyFile(sourceFile, targetPath);
}
